<template>
  <basic-container>
    <avue-crud ref="crudRef"
               v-model="form"
               v-model:page="page"
               :data="data"
               :option="option"
               :table-loading="loading"
               @on-load="onLoad"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               :before-open="beforeOpen"
               @refresh-change="refreshChange"
               @search-reset="searchChange"
               @search-change="searchChange">

    </avue-crud>

  </basic-container>
</template>

<script>
import {addCraftProcess, delCraftProcess, listCraftProcess, updateCraftProcess} from "/@/api/base/craftProcess";
import {ref,watch} from "vue";
import useCurrentInstance from "/@/utils/useCurrentInstance";
import {listProcessInfo, processInfoFindById} from "../../api/base/processInfo";
import {arraysAreEqual,} from "../../utils/validate";
import {getCraftProcessInfo} from "../../api/base/craftProcess";
import { randomId } from "@smallwei/avue";

export default {
  name: "craftProcess",

  setup: function (props) {
    const {proxy} = useCurrentInstance();

    const option = ref({
      searchMenuSpan: 6,
      tip: false,
      border: true,
      index: false,
      viewBtn: false,
      selection: true,
      addBtn: true,
      searchLabelWidth: 100,
      excelBtn: false,
      labelWidth: 100,
      column: [


        {
          label: '工艺编码',
          prop: "encode",
          model: 'input', search: true, minWidth: 150
        },
        {
          label: '工艺名称',
          prop: "name",
          model: 'input', search: true, minWidth: 150
        },
        {
          label: '状态',
          prop: "status", display: false,
          model: 'input', minWidth: 150,
        },

        {
          label: '工序明细',
          prop: "list",
          minWidth: 150,
          type: 'dynamic',
          span: 24,
          children: {
            align: 'center',
            headerAlign: 'center',
            height: 245,
            sortable: true,
            rowAdd: (done) => {
              done({id:randomId()});
            },
            rowDel: (row, done) => {
              done();
            },
            column: [
              {
                label: '工序序号',
                prop: 'sort',
                disabled: true,
              },
              {
                label: '工序名称',
                prop: 'processId',
                type: 'table',
                children: {
                  border: true,searchMenuSpan: 6,
                  column: [
                    {
                      label: '工序编码',
                      prop: "encode", minWidth: 150, search: true
                    },
                    {
                      label: '工序名称',
                      prop: "name", minWidth: 150, search: true
                    },

                    {
                      label: '工序性质',
                      prop: "quality", minWidth: 150,
                    },
                  ],

                },
                formatter: (row) => {
                  if (!row.name) return '';
                  return row.name;
                },
                onLoad: ({page, value, data}, callback) => {
                  console.log({page, value, data},"onLoad")
                  if (value) {
                    let id = value;
                    if (Array.isArray(value) && value.length > 0) {
                      id = value[0];
                    }
                    processInfoFindById({id: id}).then(res => {

                      callback(res.data);
                    })

                    return;
                  }
                  listProcessInfo(Object.assign({page: page.currentPage, limit: page.pageSize,}, data))
                      .then(res => {
                        const resData = res.data;
                        callback({
                          total: resData.total,
                          data: resData.list,
                        })
                      })

                },
                props: {
                  label: 'name',
                  value: 'id'
                },

              },
              {
                label: '工序性质',
                prop: 'quality',
                disabled: true,
              }
            ]
          }
        },

        {
          label: '备注',
          prop: "remark",
          type: 'textarea', minWidth: 150,
          span: 24,
        },

        {
          label: '申请人',
          prop: "applicantUserName",
          minWidth: 150, display: false,
        },


        {
          label: '审批人',
          prop: "approvalUserName",
          minWidth: 150, display: false,
        },

        {
          label: '录入/更新时间', prop: 'updateTime', display: false,
          search: true, searchRange: true, type: 'date',
          format: 'YYYY-MM-DD HH:mm:ss',
          searchLabelWidth: 120, minWidth: 180,
          valueFormat: 'YYYY-MM-DD HH:mm:ss',
        },

      ]
    });
    const loading = ref(true);
    const data = ref([]);
    const crudRef = ref(null);
    const selectionList = ref([]);
    const queryParams = ref({});
    const form = ref({});
    const page = ref({
      pageSize: 10,
      currentPage: 1,
      total: 0

    })
    const onLoad = (pages, params = {}) => {
      loading.value = true;
      listCraftProcess(Object.assign({
        page: pages.currentPage,
        limit: pages.pageSize,
      }, params, queryParams.value)).then(res => {
        const resData = res.data;
        page.value.total = resData.total;
        data.value = resData.list;
        loading.value = false;
        selectionClear();
      })
    }
    const selectionClear = () => {
      selectionList.value = [];
    }
    const rowSave = (row, done, loading) => {
      addCraftProcess(row).then(() => {
        done();
        onLoad(page.value);
        proxy.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    }
    const rowUpdate = (row, index, done, loading) => {
      updateCraftProcess(row).then(() => {
        done();
        onLoad(page.value);
        proxy.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    }
    const rowDel = (row) => {
      proxy.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(() => {
            return delCraftProcess(row);
          })
          .then(() => {
            onLoad(page.value);
            proxy.$message({
              type: "success",
              message: "操作成功!"
            });
          });
    }
    const refreshChange = () => {
      onLoad(page.value, queryParams.value);
    }
    const searchChange = (params, done) => {
      page.currentPage = 1;
      onLoad(page.value, params);
      done();
    }
    const beforeOpen = (done, type) => {
      if (["edit", "view"].includes(type)) {
        getCraftProcessInfo(form.value.id).then(res => {
          form.value.list = res.data || [];
        });
      }
      done();
    }


    watch(() => form.value.list, async () => {
      if (!form.value.list){return;}
      let list = JSON.parse(JSON.stringify(form.value.list));
      let i = list.filter(item => item.processId&& !item.quality).length;
      let c = 0;
      console.log(list)
      list.forEach((item,index) => {
        item.sort = index + 1;
        if (item.processId && !item.quality) {
          processInfoFindById({id: item.processId }).then(res => {
            item.quality = res.data.quality;
            item.name = res.data.name;
            c = c+1;
          })
        }
      })
      if (c ===i){
        let b = arraysAreEqual( list,form.value.list);

        if (!b){
          form.value.list = list;
        }
      }else{
        setTimeout(()=>{
          form.value.list = list;
        },500)
      }

    }, {deep: true});

    return {
      option,
      loading,
      data,
      page,
      form,
      queryParams,
      crudRef,
      onLoad,
      rowSave,
      rowUpdate,
      rowDel,
      refreshChange,
      searchChange,
      beforeOpen
    }
  }
}
</script>
